import Vue from "vue";
import * as types from "../mutation-types";
import { login } from "@/api";

const user = {
  state: {
    token: "",
    userInfo: {}
  },
  mutations: {
    [types.SET_TOKEN]: (state, param) => {
      let token = param && param.access_token;
      // let type = param && param.token_type;
      let time = param && param.expires_in;
      state.token = token;
      Vue.ls.set(types.ACCESS_TOKEN, token);
      // Vue.ls.set(types.ACCESS_TOKEN_TYPE, type);
      Vue.ls.set(types.ACCESS_TOKEN_TIME, time);
    },
    [types.CLEAN_TOKEN]: state => {
      state.token = null;
      state.userInfo = null;
      Vue.ls.remove(types.ACCESS_TOKEN);
      Vue.ls.clear();
    },
    [types.SET_USERINFO]: (state, param) => {
      state.userInfo = param;
      Vue.ls.set(types.USERINFO, param);
    }
  },
  actions: {
    // 设置用户登录态
    async Login({ commit, dispatch }, param) {
      commit(types.SET_TOKEN, param);
      try {
        await dispatch("setUserInfo");
      } catch (error) {
        // eslint-disable-next-line
        console.log(error);
      }
    },
    // 设置用户信息
    async setUserInfo({ commit }, params) {
      // try {
      //   const res = await userInfo();
      //   if (res.ack) {
      //     commit(types.SET_USERINFO, res.data);
      //   }
      // } catch (error) {
      //   // eslint-disable-next-line
      //   console.log(error);
      // }
    },
    // 刷新登录态
    async refreshToken({ commit, dispatch }) {
      try {
        // const res = await refreshToken();
        // if (res.code == 0) {
        //   dispatch("Login", res.data);
        // }
      } catch (error) {
        // eslint-disable-next-line
        console.log(error);
      }
    },
    // 退出登录 { commit }
    Logout({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.ls.remove(types.ACCESS_TOKEN);
        Vue.ls.remove(types.USERINFO);
        commit(types.CLEAN_TOKEN);
        resolve();
      });
    }
  }
};
export default user;
